# -*- encoding:utf-8 -*-
# @Time: 2022/11/9 19:30
# @Author :xibin
# @Email: xibin@maqu. com
# @File: serializers.py
# @Software: PyCharm
import re

from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from django.contrib.auth.models import User

from users.models import *


class UserDetailSerializer(ModelSerializer):
    class Meta:
        model = UserDetail
        exclude = ['is_delete']
        extra_kwargs = {  #约束
            'avatar':{'read_only':True},
            'user':{'required':False,'write_only':True}
        }

class UserSerializer(ModelSerializer):
    userdetail = UserDetailSerializer(required=False,read_only=True)

    class Meta:
        model = User
        exclude = ['password','last_name']

    extra_kwargs = {
        'id':{'read_only':True},  #只读
        'last_login':{'read_only':True},
        'is_superuser':{'read_only':True},
        'is_staff':{'read_only':True},
        'is_active':{'read_only':True},
        'groups':{'read_only':True},
        'date_joined':{'read_only':True},
    }

class UpdatePasswordSerializer(serializers.Serializer):
    password = serializers.CharField(max_length=30,label='原密码')
    new_password = serializers.CharField(max_length=30,label='新密码')
    re_new_password = serializers.CharField(max_length=30,label='确认密码')

    def validate(self,attrs):  #检验
        if attrs['new_password'] != attrs['re_new_password']:
            raise serializers.ValidationError('两次密码输入不一致')
        return attrs

class AreaSerializer(ModelSerializer): #所有的省
    """行政区划自身序列化器"""
    class Meta:
        model = Area
        fields = ['id','name']

class ParentSerializer(ModelSerializer): #哪个省有那些市，或者那个市有那些区
    """行政区划自身序列化器及子级区划"""
    area_set = AreaSerializer(many=True,read_only=True) #外键字段，

    class Meta:
        model = Area
        fields = ['id','name','area_set']

class AddressSerializer(ModelSerializer):
    province_name = serializers.CharField(source='province.name',read_only=True)
    city_name = serializers.CharField(source='city.name',read_only=True)
    district_name = serializers.CharField(source='district.name',read_only=True)

    class Meta:
        model = Address
        exclude = ['is_delete']

    def validated_mobile(self,value): #格式是validated加字段名
        if not re.match(r'1[3-9]\d{9}$',value):
            raise serializers.ValidationError('手机号码格式错误')
        return value

